package com.start.dataSource.register;


import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.start.dataSource.entity.StartDataSource;
import com.start.dataSource.service.StartDataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class StartDataSourceRegister implements CommandLineRunner {

    @Autowired
    private DynamicDataSourceProperties dynamicDataSourceProperties;
    @Autowired
    private StartDataSourceService startDataSourceService;

    @Override
    public void run(String... args) {
        if (dynamicDataSourceProperties == null) return;
        Map<String, DataSourceProperty> datasource = dynamicDataSourceProperties.getDatasource();
        List<StartDataSource> list = new ArrayList<>();
        datasource.forEach((key, value) -> list.add(StartDataSource.create(key, value)));
        LambdaQueryWrapper<StartDataSource> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StartDataSource::getIsSystem, 1);
        List<StartDataSource> sourceList = startDataSourceService.list(wrapper);
        Map<String, StartDataSource> collect = sourceList.stream().collect(Collectors.toMap(StartDataSource::getKeyFlag, e -> e));
        List<StartDataSource> addList = list.stream().filter(e -> !collect.containsKey(e.getKeyFlag())).collect(Collectors.toList());
        List<StartDataSource> updateList = new ArrayList<>();
        list.stream().filter(e -> collect.containsKey(e.getKeyFlag())).
                forEach(e -> {
                    e.setId(collect.get(e.getKeyFlag()).getId());
                    e.setCreateBy("sys_admin");
                    updateList.add(e);
                });
        addList.addAll(updateList);
        if (addList.isEmpty()) return;
        startDataSourceService.saveOrUpdateBatch(addList);
    }
}
